<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="入库ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入入库ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="样品组名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入样品组名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="样品组编号" prop="projectCode">
        <el-input
          v-model="queryParams.projectCode"
          placeholder="请输入样品组编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接样日期">
        <el-date-picker
          v-model="daterangeWarehousingDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="收样编号" prop="warehousingCode">
        <el-input
          v-model="queryParams.warehousingCode"
          placeholder="请输入收样编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="送样人ID" prop="senderId">
        <el-input
          v-model="queryParams.senderId"
          placeholder="请输入送样人ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="送样人名称" prop="senderName">
        <el-input
          v-model="queryParams.senderName"
          placeholder="请输入送样人名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['custom:warehousing:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['custom:warehousing:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['custom:warehousing:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="warehousingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库ID" align="center" prop="id" />
      <el-table-column label="样品组名称" align="center" prop="projectName" />
      <el-table-column label="样品组编号" align="center" prop="projectCode" />
      <el-table-column label="接样日期" align="center" prop="warehousingDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.warehousingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收样编号" align="center" prop="warehousingCode" />
      <el-table-column label="送样人ID" align="center" prop="senderId" />
      <el-table-column label="送样人名称" align="center" prop="senderName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['custom:warehousing:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['custom:warehousing:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工单样品接收入库登记对话框 -->
    <el-dialog title="修改样品入库单" v-model="open" width="1500px" append-to-body>
      <!--父-->
      <el-card class="box-card">
        <el-row :gutter="15">
          <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px">
            <el-col :span="23">
              <el-row :gutter="15">
                <el-col :span="12">
                  <el-form-item label="样品组名称" prop="projectName">
                    <el-input v-model="form.projectName" placeholder="请输入样品组名称" :maxlength="100" clearable
                    :style="{width: '100%'}"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="样品组编号" prop="projectCode">
                    <el-input v-model="form.projectCode" placeholder="请输入样品组编号" :maxlength="100" clearable
                    :style="{width: '100%'}"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="接样日期" prop="warehousingDate">
                    <el-date-picker v-model="form.warehousingDate" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" :style="{width: '100%'}" placeholder="请选择接样日期" clearable>
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="接样编号" prop="warehousingCode">
                    <el-input v-model="form.warehousingCode" placeholder="请输入接样编号" :maxlength="100" clearable
                    :style="{width: '100%'}"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="送样人" prop="senderId">
                    <el-select v-model="form.senderId" filterable clearable placeholder="请选择送样人">
                      <el-option
                        v-for="item in senderOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入多行文本" :maxlength="200"
                    :autosize="{minRows: 2, maxRows: 4}" :style="{width: '100%'}"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-form>
        </el-row>
      </el-card>
      <!--子-->
      <el-card class="box-card">
        <h3 style="padding: 10px 30px; font-weight: 550; font-size: 22px;">样品入库登记明细</h3>
        <el-table :data="tableData" border style="width: 100%;">
          <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
          <el-table-column prop="receiveId" label="收样编号" width="140">
            <template #default="scope">
              <el-input v-model="scope.row.receiveId" placeholder="请输入收样编号"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="inspectionDepartment" label="送检单位名称" width="140">
            <template #default="scope">
              <el-input v-model="scope.row.inspectionDepartment" placeholder="请输入送检单位名称"></el-input>
            </template>
        </el-table-column>
          <el-table-column prop="sampleName" label="样品名称" width="140">
            <template #default="scope">
              <el-input v-model="scope.row.sampleName" placeholder="请输入样品名称"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="sampleCount" label="样品数量" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.sampleCount" type="number" :min="1"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="detectionProjectName" label="检测样品组名称" width="180">
            <template #default="scope">
              <el-input v-model="scope.row.detectionProjectName" placeholder="请输入检测样品组名称"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="detectionProjectCode" label="检测样品组代码" width="140">
            <template #default="scope">
              <el-input v-model="scope.row.detectionProjectCode" placeholder="请输入检测样品组代码"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注">
            <template #default="scope">
              <el-input v-model="scope.row.remark" type="textarea" :rows="2" placeholder="请输入备注"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" align="center">
            <template #default="scope">
              <el-button size="small" type="text" icon="Delete" @click="deleteOneRow(scope.$index)" :disabled="tableData.length <= 1">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="padding: 20px 0;">
          <el-button type="primary" @click="addOneRow">新增明细行</el-button>
        </div>
      </el-card>
      <!--确认和取消按钮-->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listWarehousing, getWarehousing, delWarehousing, updateWarehousing } from "@/api/custom/warehousing"
import { getDetailsByParentId } from "@/api/custom/warehousing_child"
import { getAllUsers } from "@/api/user/user"

export default {
  name: "Warehousing",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单样品接收入库登记表格数据
      warehousingList: [],
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeWarehousingDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        projectName: null,
        projectCode: null,
        warehousingDate: null,
        warehousingCode: null,
        senderId: null,
        senderName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 可选用户列表
      senderOptions: [],
      // 明细列表
      tableData: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询工单样品接收入库登记列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeWarehousingDate && '' != this.daterangeWarehousingDate) {
        this.queryParams.params["beginWarehousingDate"] = this.daterangeWarehousingDate[0]
        this.queryParams.params["endWarehousingDate"] = this.daterangeWarehousingDate[1]
      }
      listWarehousing(this.queryParams).then(response => {
        this.warehousingList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectName: null,
        projectCode: null,
        warehousingDate: null,
        warehousingCode: null,
        senderId: null,
        senderName: null,
        remark: null
      }
      this.resetForm("form")
      this.tableData = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeWarehousingDate = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      // 查询可选用户
      getAllUsers().then(res => {
        this.senderOptions = []
        res.data.forEach(v => {
          this.senderOptions.push({
            value: v.userId,
            label: v.userName
          })
        })
      })
      // 根据ID查询当前入库单信息
      getWarehousing(id).then(response => {
        this.form = response.data
        this.open = true
      })
      // 查询明细
      getDetailsByParentId(id).then(res => {
        this.tableData = res.data
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return
        // 处理送样人名称
        let user = this.senderOptions.find(v => v.value == this.form.senderId)
        this.form.senderName = user.label || undefined
        // 发送请求
        updateWarehousing({
          sampleWarehousing: this.form,
          sampleRecevieWarehousingList: this.tableData
        }).then(response => {
          this.$modal.msgSuccess("修改成功")
          this.open = false
          this.getList()
        })
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除工单样品接收入库登记编号为"' + ids + '"的数据项？').then(function() {
        return delWarehousing(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('custom/warehousing/export', {
        ...this.queryParams
      }, `warehousing_${new Date().getTime()}.xlsx`)
    },
    /** 新增一行 */
    addOneRow() {
      this.tableData.push({
        inspectionDepartment: '',
        sampleName: '',
        sampleCount: 1,
        detectionProjectName: "",
        detectionProjectCode: "",
        remark: ""
      })
    },
    /** 删除一行 */
    deleteOneRow(idx) {
      this.tableData = this.tableData.filter((value, index, array) => index !== idx)
    }
  }
}
</script>

<style>
.box-card {
  margin: 0 20px 20px 20px;
}
</style>
